package rpc

import (
	"bytes"
	"capnproto.org/go/capnp/v3"
	books "gin-capnprotodemo/book"
)

func EncodeBookMessage(title string, pageCount int32) ([]byte, error) {
	// Make a brand new empty message.  A Message allocates Cap'n Proto structs.
	msg, seg, err := capnp.NewMessage(capnp.SingleSegment(nil))
	if err != nil {
		return nil, err
	}

	// Create a new Book struct.  Every message must have a root struct.
	book, err := books.NewRootBook(seg)
	if err != nil {
		return nil, err
	}
	if err := book.SetTitle(title); err != nil {
		return nil, err
	}
	book.SetPageCount(pageCount)

	// Encode the message.
	var buf bytes.Buffer
	err = capnp.NewEncoder(&buf).Encode(msg)
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func DecodeBookMessage(data []byte) (string, int32, error) {
	// Decode the message.
	r := bytes.NewReader(data)
	msg, err := capnp.NewDecoder(r).Decode()
	if err != nil {
		return "", 0, err
	}

	// Extract the root struct from the message.
	book, err := books.ReadRootBook(msg)
	if err != nil {
		return "", 0, err
	}

	// Access fields from the struct.
	title, err := book.Title()
	if err != nil {
		return "", 0, err
	}
	pageCount := book.PageCount()

	return title, pageCount, nil
}
